package org.login;

import lombok.extern.slf4j.Slf4j;
import org.common.BaseMain;
import org.common.CommonConfig;
import org.common.dispatcher.ProtoDispatcher;
import org.common.mongo.MongoService;
import org.common.redis.RedisService;
import org.common.utils.ClassScannerUtils;
import org.common.utils.SpringUtils;
import org.common.akka.AkkaContext;
import org.common.netty.NettyServer;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Set;

@Slf4j
@Component
public class LoginMain extends BaseMain {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LoginBeanConfig.class);
        context.start();

        LoginMain loginMain = SpringUtils.getBean(LoginMain.class);
        loginMain.init();

        System.exit(0);
    }

    @Override
    protected void initServer() {
        CommonConfig commonConfig = SpringUtils.getBean(CommonConfig.class);
        // actor初始化
        AkkaContext.initActorSystem();
        // mongo服务启动
        MongoService mongoService = SpringUtils.getBean(MongoService.class);
        mongoService.initMongoService(commonConfig.getMongoHost(), commonConfig.getMongoUser(), commonConfig.getMongoPassword(), commonConfig.getLoginDbName());
        // redis服务启动
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        redisService.initRedisService(commonConfig.getRedisHost(), commonConfig.getRedisPassword());

        // 协议转发器初始化
        try {
            Set<Class<?>>  classes = ClassScannerUtils.getClasses("org.login");
            ProtoDispatcher protoDispatcher = SpringUtils.getBean(ProtoDispatcher.class);
            protoDispatcher.load(classes);
        } catch (IOException | URISyntaxException | ClassNotFoundException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        LoginConfig loginConfig = SpringUtils.getBean(LoginConfig.class);
        // 对内netty启动
        NettyServer innerNettyServer = SpringUtils.getBean("innerNettyServer");
        innerNettyServer.start(loginConfig.getInnerPort(), "tcp");

        // 对外netty启动
        NettyServer playerNettyServer = SpringUtils.getBean("playerNettyServer");
        playerNettyServer.start(loginConfig.getPlayerPort(), commonConfig.getProtoType());

        log.info("LoginServer start!");
    }

    @Override
    protected void handleBackGroundCmd(String cmd) {

    }

    @Override
    protected void onShutdown() {
        log.warn("LoginServer is ready to shutdown.");
    }
}